using System;
using Gtk;
using System.Xml;
using System.IO;
using TheWeather.www.webservicex.net;

public partial class MainWindow: Gtk.Window
{	
		
		GlobalWeather ws = new GlobalWeather ();
		int contadorDeCiudades =0;
		

	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		InicializarTheWeather();
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
		
	}


//	protected void OnMinimizeEvent (object sender, MinimizeEventArgs a)
//	{
//	
//	    MessageDialog aviso = new MessageDialog (null, 
//                                   DialogFlags.DestroyWithParent,
//                                   MessageType.Info, 
//                                   ButtonsType.Close, "Hemos minimizado !!!!");
//                                   
//       
//		int result = aviso.Run ();
//		aviso.Destroy();
//	}
	
	
	protected void exit (object sender, System.EventArgs a )
	{
		//this.exit(sender, a);
		this.Iconify();
	 	this.Hide();
		
	}
	
	
	protected void InicializarTheWeather()
	{
		
		
		EventBox eb = new EventBox();
		eb.Add(new Image(Stock.MissingImage, IconSize.Menu)); // using stock icon
		// hooking event
		eb.ButtonPressEvent += new ButtonPressEventHandler (this.OnImageClick);
		Egg.TrayIcon icon = new Egg.TrayIcon("Test");
		icon.Add(eb);
		// showing the trayicon
		icon.ShowAll();
		
		try
		{
		
			StreamReader SR = new StreamReader ("theweather.cfg");
			int pais,ciudad;
			pais = Convert.ToInt32(SR.ReadLine());
			ciudad = Convert.ToInt32(SR.ReadLine());
		
			if (pais > 0)
				{
				cmbPaises.Active=pais;
				cmbCiudades.Active = ciudad;
				}
	
			SR.Close();
			}
		
		catch(Exception e)
		{
		}
		
		
		
	}
	
	private void OnImageClick (object o, ButtonPressEventArgs args) // handler for mouse click
	{
   		if (args.Event.Button == 3) //right click
   		 {
      		Menu popupMenu = new Menu(); // creates the menu  
                // creates a menu item with no image as default
      		ImageMenuItem menuActualizar = new ImageMenuItem ("Actualizar");
      		ImageMenuItem menuPopup1 = new ImageMenuItem ("Salir");
      		
      		
                // creates a image for the menu item

      		Image appActualizarimg = new Image(Stock.Refresh , IconSize.Menu );
      		menuActualizar.Image = appActualizarimg; // sets the menu item's image
      		popupMenu.Add(menuActualizar); // adds the menu item to the menu
      		

      		Image appimg = new Image(Stock.Quit, IconSize.Menu);
      		menuPopup1.Image = appimg; // sets the menu item's image
      		popupMenu.Add(menuPopup1); // adds the menu item to the menu
      		
      		   

            
               
               // hooks a event when the user clicks the icon
      	menuPopup1.Activated += new EventHandler(this.OnPopupClick);
		
		menuActualizar.Activated += new EventHandler(this.OnActualizarClick);
		
		popupMenu.ShowAll(); // shows everything
                // pops up the actual menu when the user right clicks
      		popupMenu.Popup(null, null, null, IntPtr.Zero, args.Event.Button, args.Event.Time);
   		}
   		
   		
   		if (args.Event.Button == 1) //left click
   		{
   		
   		this.Deiconify ();
   		this.Show();
   		}
	}
	
	
	private void OnPopupClick(object o, EventArgs args)
	{
		Application.Quit(); // quits the application when the users clicks the popup menu
	}
	
	private void OnActualizarClick(object o, EventArgs args)
	{
	 // Escribir aqui lo que quieres que haga
	 
	 getData(this,null);
	
	 
	}
	
	/**********************************************************************
	*************** Obtenemos el nombre de las ciudades del WS ************
	**********************************************************************/
	
	protected void GetCities (object sender, System.EventArgs a )
	{

	cmbCiudades.Visible= true;
	
	//Obtenemos las ciudades
	try
		{
		System.Xml.XmlTextReader readerCiudades= new XmlTextReader(new System.IO.StringReader(ws.GetCitiesByCountry(cmbPaises.ActiveText)));
	
		//Borramos las ciudades del anterior pais seleccionado
		for (int i=contadorDeCiudades;i>0;i--)
			{
			cmbCiudades.RemoveText (i);	
			}
		cmbCiudades.RemoveText (0);
		
		
		
		//cmbCiudades.Clear();
		
		
		//Introducimos las nuevas
	 	while (readerCiudades.Read ())
			{	
			if (readerCiudades.Name == "City")
	                                {
	                              
	                                	String City=readerCiudades.ReadString().ToString(); 
	                                	cmbCiudades.AppendText(City);
	                                	//cmbCiudades.InsertText(contadorDeCiudades, City);
	                                	contadorDeCiudades++; //Chivato para poder borrar luego las ciudades
	                                }
			}
		
			}
		
		
	catch (Exception e)
		{
		
		MessageDialog aviso = new MessageDialog (null, 
                                   DialogFlags.DestroyWithParent,
                                   MessageType.Info, 
                                   ButtonsType.Close, "No se han podido obtener las ciudades.\nRevise su conexion de internet");
                                   
       
		int result = aviso.Run ();
		aviso.Destroy();
		
		}
	
	}

	
	/**********************************************************************
	*************** Obtenemos los datos de la ciudad  *********************
	**********************************************************************/
	
	protected virtual void getData(object sender, System.EventArgs e)
	{
	
		txtHora.Visible = true;
   		txtViento.Visible = true;			
      	txtVisibilidad.Visible = true;			
   		txtTemperatura.Visible = true;
		txtRocio.Visible = true;
		txtHumedad.Visible = true;
		txtPresion.Visible = true;
   		lblViento.Visible = true;			
      	lblVisibilidad.Visible = true;			
   		lblTemperatura.Visible = true;
		lblRocio.Visible = true;
		lblHumedad.Visible = true;
		lblPresion.Visible = true;
	
	//Obtenemos los datos	
	System.Xml.XmlTextReader readerDatos= new XmlTextReader(new System.IO.StringReader( ws.GetWeather(cmbCiudades.ActiveText,cmbPaises.ActiveText)));
	//Console.WriteLine( ws.GetWeather(ciudades.ActiveText, combobox3.ActiveText ));

	try
	{
	readerDatos.Read();
	//readerDatos.ReadElementString();
	//Console.WriteLine("Result:" + readerDatos.Read());	
	
		//Seleccionamos el tipo de dato de la Ciudad
		while (!readerDatos.EOF)
		{	
		
		readerDatos.Read ();
		switch (readerDatos.Name)
		{
			case "Location":
				//String lugar, aeropuerto,gps = "";
				String location=readerDatos.ReadString();
           		txtLocalizacion.Text=location.ToString();
           	
           		//ToDO List:
           		//Obtener el monbre del aeropuerto, va entre ( )
           		//Obtener Coodenadas GPS, va seguido de ") "
           	
           		//lugar = location.
           		
			break;
			
			case "Time":
           		txtHora.Text=readerDatos.ReadString();
			break;
			
			case "Wind":
				String wind=readerDatos.ReadString();
           		txtViento.Text=wind.ToString();	
			    //txtviento.Text=readerDatos.ReadString();
			break;
			
			case "Visibility":
		      	txtVisibilidad.Text=readerDatos.ReadString();
			break;	
			
			case "Temperature":
           		String Temperature=readerDatos.ReadString();
           		txtTemperatura.Text=Temperature.ToString();
			break;
			
			case "DewPoint":
		 		txtRocio.Text=readerDatos.ReadString();
			break;
			
			case "RelativeHumidity":
		 		txtHumedad.Text=readerDatos.ReadString();
			break;
			
			case "Pressure":
		 		txtPresion.Text=readerDatos.ReadString();
			break;
		
		  } // End of switch
		 
	
    	 }//End of while
	
	}
	catch (Exception ex)
	{
		txtLocalizacion.Text = "No existen datos sobre esta localidad";
		txtHora.Visible = false;
   		txtViento.Visible = false;			
      	txtVisibilidad.Visible = false;			
   		txtTemperatura.Visible = false;
		txtRocio.Visible = false;
		txtHumedad.Visible = false;
		txtPresion.Visible = false;
   		lblViento.Visible = false;			
      	lblVisibilidad.Visible = false;			
   		lblTemperatura.Visible = false;
		lblRocio.Visible = false;
		lblHumedad.Visible = false;
		lblPresion.Visible = false;
	
	}
	
	readerDatos.Close();
	
	}
	

	//···································································
	//··················  Guarda la configuracion·······················
	//···································································

	protected virtual void guardar(object sender, System.EventArgs e)
	{
	
		StreamWriter SW;
		SW=File.CreateText("theweather.cfg");
		SW.WriteLine(cmbPaises.Active);
		SW.WriteLine(cmbCiudades.Active );
		SW.Close();
	}


	
	
}